package com.tang.imgupload.controller;

import com.tang.imgupload.Entity.ImgInfo;
import com.tang.imgupload.commen.CommenResult;
import com.tang.imgupload.commen.Constant;
import com.tang.imgupload.service.IImgService;
import com.tang.imgupload.service.IIvokePyService;
import com.tang.imgupload.util.FastDFSUtil;
import com.tang.imgupload.util.FormatCheck;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.util.List;


@RestController
@RequestMapping(value = "/image")
public class ImgController {

	private static final Logger logger = LogManager.getLogger(ImgController.class);
	@Resource
	IImgService imgService;
	@Resource
	IIvokePyService iIvokePyService;
	@Resource
	FastDFSUtil fastDFSUtil;

	/**
	 * 上传图像
	 *
	 * @param file   文件域
	 * @param userId 用户名
	 * @return
	 */
	@PostMapping(value = "/user/{userId}")
	public CommenResult upload(@RequestParam("file") MultipartFile file, @PathVariable("userId") String userId){
		if(file.isEmpty()){
			return CommenResult.failAndMsg(Constant.CommenResult.FILE_EMPTY);
		}
		if(userId.isEmpty()){
			return CommenResult.fail();
		}
		//获得文件名
		String fileName = file.getOriginalFilename();
		if(fileName == null || fileName.length() <= 0 || fileName.length() > 255){
			return CommenResult.failAndMsg(Constant.CommenResult.FILE_NAME_ERROR);
		}
		String fileFormat = fileName.substring(fileName.lastIndexOf("."));
		//图像文件格式校验
		if(!FormatCheck.checkImg(fileFormat)){
			return CommenResult.failAndMsg(Constant.CommenResult.FILE_FORMAT_ERROR);
		}
		//保存文件
		String newFileName = null;
		try {
			newFileName = fastDFSUtil.uploadFile(file);
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
		if(newFileName == null){
			return CommenResult.failAndMsg(Constant.CommenResult.FILE_SAVE_ERROR);
		}
		// 生成图像信息
		ImgInfo imgInfo = new ImgInfo(null, userId, fileName, newFileName,
		                              new Date(System.currentTimeMillis()), new Time(System.currentTimeMillis()));
		//写入到数据库

		int k = imgService.saveImg(imgInfo);
		if(k <= 0){
			return CommenResult.failAndMsg(Constant.CommenResult.SQL_INSERT_ERROR);
		}
		//写入到redis缓存,value为新文件名+"-"+原文件名
		imgService.cacheImg(userId, imgInfo.getNewName(),
		                    Constant.INTEGER.Day.getValue());
		return CommenResult.succAndData(imgInfo);
	}

	/**
	 * 查指定图像信息
	 *
	 * @param id 图像记录id
	 * @return
	 */
	@GetMapping(value = "/api/{id}")
	public CommenResult findImg(@PathVariable("id") Long id){
		ImgInfo imgInfo = imgService.getImg(id);
		return CommenResult.succAndData(imgInfo);
	}

	@GetMapping(value = "/user/{userId}")
	public CommenResult findImgAll(@PathVariable("userId") String userId){
		// 查缓存
		List<Object> cacheImg = imgService.getCacheImg(userId);
		if(cacheImg.size() > 0){
			return CommenResult.succAndData(cacheImg);
		}
		// 查数据库
		List<String> imgs = imgService.getImgs(userId);
		if(imgs == null || imgs.size() <= 0){
			return CommenResult.failAndMsg(Constant.CommenResult.SQL_SELECT_ERROR);
		}
		return CommenResult.succAndData(imgs);
	}

	/**
	 * 转发给消息队列，调用py算法
	 *
	 * @param picpath 文件名
	 * @return
	 */
	@PostMapping(value = "/srcnn")
	public CommenResult SRCNN(@RequestParam("picpath") String picpath){
		if(iIvokePyService.invokeSRCNN(picpath)){
			return CommenResult.succ();
		}else{
			return CommenResult.failAndMsg(Constant.CommenResult.MQ_SEND_EXCEPTION);
		}
	}
}
